<template>
  <el-drawer
    :title="title"
    v-model="visible"
    direction="rtl"
    :before-close="handleClose"
    size="80%">
    <div class="box-bg-color">
      <div class="filter-container">
        <div class="filter-item">
          <el-input v-model="searchReq.name" placeholder="请输入硬件名称" style="width: 200px" clearable></el-input>
        </div>
        <div class="filter-item">
          <el-input v-model="searchReq.supplierName" placeholder="请输入供应商名称" style="width: 200px" clearable></el-input>
        </div>
        <div class="filter-item">
          <el-input v-model="searchReq.technologyChargePerson" placeholder="请输入技术负责人" style="width: 200px" clearable></el-input>
        </div>
        <div class="filter-item">
          <el-input v-model="searchReq.purchaseChargePerson" placeholder="请输入采购负责人" style="width: 200px" clearable></el-input>
        </div>
        <div class="filter-item">
          <el-input v-model="searchReq.examinePerson" placeholder="请输入审核负责人" style="width: 200px" clearable></el-input>
        </div>
        <div class="filter-item">
          <el-input v-model="searchReq.phone" placeholder="请输入客户手机号" style="width: 200px" clearable></el-input>
        </div>
        <div class="filter-item">
          <el-select v-model="searchReq.type" clearable style="width: 180px" placeholder="请选择订单类型">
            <el-option v-for="item in orderTypeList" :key="item.value" :label="item.label" :value="item.value">
              <k-badge :type="item.type" :content="item.label"></k-badge>
            </el-option>
          </el-select>
        </div>
        <div class="filter-item">
          <el-date-picker
            v-model="searchDate"
            type="datetime"
            placeholder="选择下单时间"
            @change="dateEvent"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
        <div class="filter-item">
          <el-button type="primary" @click="searchEvent">搜索</el-button>
        </div>
      </div>

      <k-table
        ref="tableRef"
        v-bind="tableData"
        :callback="getEquipmentListApi"
        :loading="loading"
        stripe
        current-row-key="id"
      >
        <template #type="{ row }">
          <k-badge
            :type="row.typeInfo.type"
            :content="row.typeInfo.label"
          ></k-badge>
        </template>
        <template #status="{ row }">
          <k-badge
            :type="row.statusInfo.type"
            :content="row.statusInfo.label"
          ></k-badge>
        </template>
        <template #courierCompanyName="{ row }">
          <span class="link-type" v-if="row.courierCompany !== '' && row.courierNumber !== ''" @click="clickExpressEvent(row)">{{ row.courierCompanyName }}</span>
          <span v-else>{{ row.courierCompanyName }}</span>
        </template>
        <!-- <template #actions="{ row }">
          <el-button type="primary" plain size="small" @click="clickEditEvent(row.id)" v-perm="'equipment:index:edit'"
            >编辑</el-button
          >
          <el-button type="info" plain size="small" @click="clickDeleteEvent(row)" v-perm="'equipment:index:delete'"
          >删除</el-button>
          <el-button
            type="primary"
            plain
            size="small"
            @click="clickAuditEvent(row.id)"
            v-if="row.status === 2"
            v-perm="'equipment:index:updateStatus'"
          >审核</el-button>
        </template> -->
      </k-table>

      <!-- 硬件录入编辑 -->
      <!-- <Edit v-model="showEdit" :curr-id="currId" @change="updatePartnerSuccess"></Edit> -->

      <!-- 硬件录入添加 -->
      <!-- <Add v-model="showAdd" @change="createPartnerSuccess"></Add> -->

      <!-- 硬件录入审核 -->
      <!-- <Audit v-model="showAudit" :curr-id="currId" @change="createPartnerSuccess"></Audit> -->

      <!-- 硬件物流快递信息 -->
    <Express v-model="showExpress" :courierCompanyName="courierCompanyName" :courierNumber="courierNumber" :curr-id="equipmentId"></Express>
    </div>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, watch, type PropType, nextTick } from 'vue'
import { UPDATE_MODEL_EVENT } from 'cm/contants'
import type { IKTableProps } from 'k-ui'
import { confirmElBox, dateStrFormat, downLoad } from '@/utils'
import { hasPerms } from '@/utils/perm'
import Express from '@/views/equipmentAdmin/equipment/components/express.vue'
import { useApiLock } from '_hooks'
import type { ListResultData, Pagination } from '@/api/base'

import {
  getEquipmentList,
  updateStatus,
  type QueryEquipmentList,
  type EquipmentApiResult
} from '@/api/equipment'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
    default: false
  },
  currId: {
    type: String,
    required: true,
    default: ''
  },
  type: {
    type: String,
    required: true,
    default: ''
  },
  customerName: {
    type: String,
    required: true,
    default: ''
  }
})

const emit = defineEmits([UPDATE_MODEL_EVENT, 'change'])

const visible = ref<boolean>(false)

const tableRef = ref()
const tableData = ref<IKTableProps<EquipmentApiResult>>({
  mode: 'config',
  data: { list: [], total: 0 },
  auto: false,
  isPager: true,
  pageSize: 20,
  index: true,
  columns: [
    { label: '硬件名称', prop: 'name', default: '--' },
    { label: '数量', prop: 'number', default: '--' },
    { label: '客户名称', prop: 'customerName', default: '--' },
    { label: '供应商名称', prop: 'supplierName', default: '--' },
    { label: '技术负责人', prop: 'technologyChargePerson', default: '--' },
    { label: '审核负责人', prop: 'examinePerson', default: '--' },
    { label: '快递公司', prop: 'courierCompanyName', default: '--', minWidth: 160, slot: true },
    { label: '订单类型', prop: 'type', slot: true },
    { label: '订单状态', prop: 'status', slot: true },
    {
      label: '下单日期',
      prop: 'orderDate',
      formatter: (row: EquipmentApiResult) => dateStrFormat(row.orderDate as string),
      width: 100
    },
    {
      label: '创建时间',
      prop: 'createDate',
      formatter: (row: EquipmentApiResult) => dateStrFormat(row.createDate as string),
      width: 100
    }
  ]
})

const orderTypeList = ref<Array<any>>([{
  label: '退货',
  value: 'return',
  type: 'danger'
},
{
  label: '换货',
  value: 'barter',
  type: 'warning'
},
{
  label: '发货',
  value: 'deliver',
  type: 'primary'
}])

const statusList = ref<Array<any>>([{
  label: '审核中',
  value: 2,
  type: 'danger'
},
{
  label: '审核不通过',
  value: 0,
  type: 'warning'
},
{
  label: '审核通过',
  value: 1,
  type: 'primary'
}])

const handleClose = () => {
  tableData.value.data.list = []
  emit(UPDATE_MODEL_EVENT, false)
}
const loading = ref<boolean>(false)

const searchReq = ref<QueryEquipmentList>({
  page: 1,
  size: 20,
  name: '',
  customerId: '',
  supplierName: '',
  technologyChargePerson: '',
  purchaseChargePerson: '',
  examinePerson: '',
  phone: '',
  type: '',
  orderDate: '',
})
// 查询表格事件
const queryReq = ref<QueryEquipmentList>({ page: 1, size: 20 })

const getEquipmentListApi = async ({ page, size }: Pagination) => {
  loading.value = true
  const res = await useApiLock(() => getEquipmentList({ ...queryReq.value, page, size } as QueryEquipmentList), 500)
  loading.value = false
  if (res?.code === 200) {
    const data = res.data as ListResultData<EquipmentApiResult>
    data.list.forEach((item: any) => {
      item.typeInfo = orderTypeList.value.find((oItem: any) => oItem.value === item.type)
      item.statusInfo = statusList.value.find((oItem: any) => oItem.value === item.status)
    })
    tableData.value.data = data
  } else {
    ElMessage({ message: res?.msg || '网络异常，请稍后重试', type: 'error' })
  }
}

const updateSuccess = (newPage = {}) => {
  // 在当前页 重新加载数据
  nextTick(() => {
    tableRef.value.refreshData(newPage)
  })
}

// 标题
const title = ref<string | undefined>(undefined)

// 查看物流信息
const equipmentId = ref<string | undefined>(undefined)
const showExpress = ref<boolean>(false)
const courierNumber = ref<string>()
const courierCompanyName = ref<string>()
const clickExpressEvent = (row: EquipmentApiResult) => {
  equipmentId.value = row.id
  courierNumber.value = row.courierNumber
  courierCompanyName.value =row.courierCompanyName
  showExpress.value = true
}

watch(
  () => props.modelValue,
  async () => {
    visible.value = props.modelValue
    if (props.modelValue && props.currId) {
      searchReq.value.type = props.type
      searchReq.value.customerId = props.currId
      queryReq.value = Object.assign({}, searchReq.value)
      updateSuccess({ page: 1, size: 10 })
      const titleLabel = orderTypeList.value.find((item: any) => item.value ===  props.type)?.label
      title.value = `${props.customerName} - ${titleLabel}记录`
    }
  }
)

const searchEvent = () => {
  queryReq.value = Object.assign({}, searchReq.value)
  updateSuccess({ page: 1, size: 10 })
}

const searchDate = ref('')

const dateEvent = async (e: any) => {
  if (e) {
    searchReq.value.orderDate = e
  } else {
    searchReq.value.orderDate = undefined;
  }
}
</script>
